import Conversation from '@/components/Conversation';
import GoodsDiv from '@/components/GoodsDiv';
import RightFixed from '@/layouts/RightFixed';
import TopBread from '@/layouts/TopBread';
import { allGoodsByCompany, allGoodsBySaleMonth } from '@/services/commodity';
import { colorStr, getQueryParams } from '@/utils/utils';
import { Collapse, Descriptions, Image, Pagination, Popover } from 'antd';
import moment from 'moment';
import { useCallback, useEffect, useState } from 'react';
import { history } from 'umi';
import styles from './index.less';

const SaleOne: React.FC = () => {
  const business = history?.location?.query;
  const qs = getQueryParams();
  const [color, setColor] = useState<string>(localStorage.getItem('color') || '#1a7721');
  const { Panel } = Collapse;
  const [list, setList] = useState<any[]>([]);
  const [goodsList, setGoodsList] = useState<any[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [conversation, setConversation] = useState<boolean>(false);
  let current = JSON.stringify(business?.intoPicture)
    .replace('[', '')
    .replace(']', '')
    .replace(/"/g, '')
    .replace(/\\/g, '')
    .split(',');
  const panelStyle = {
    borderRadius: 5,
    borderBottom: '1px soild #E8A95B',
  };

  const getList = useCallback(async () => {
    try {
      await allGoodsBySaleMonth({ companyId: business?.id }).then((res) => {
        let curr: any[] = [];
        res.list.map((item: any, index: number) => {
          if (index < 5 && item.month !== 0) {
            curr.push(item);
          }
        });
        setList(curr);
      });
    } catch (error) {
      console.log(error);
    }
  }, [business?.id]);

  useEffect(() => {
    getList();
  }, [getList]);

  // 获取商品列表
  const getGoodsList = useCallback(async () => {
    try {
      await allGoodsByCompany({
        companyId: business?.id,
        pageIndex: currentPage,
        pageSize: 12,
      }).then((res) => {
        setGoodsList(res.list);
        setTotal(res.total);
      });
    } catch (error) {
      console.log(error);
    }
  }, [business?.id, currentPage]);

  useEffect(() => {
    getGoodsList();
  }, [getGoodsList]);

  const shopOne = [
    { key: 0, name: '店铺名称', value: business?.saleName },
    {
      key: 1,
      name: '创建时间',
      value: `${moment(Number(business?.timeAdd)).format('YYYY-MM-DD HH:mm:ss')}`,
    },
    {
      key: 2,
      name: '店铺地址',
      value: `${business?.province} ${business?.city} ${business?.area}`,
    },
    { key: 3, name: '经营类目', value: '保健品' },
    { key: 4, name: '掌柜名字', value: business?.nickname },
    { key: 5, name: '联系邮箱', value: business?.mail },
  ];

  const content = (
    <div>
      <p
        onClick={() => {
          setConversation(true);
        }}
        style={{ cursor: 'pointer', margin: 0 }}
      >
        店铺客服
      </p>
    </div>
  );

  const getFields = () => {
    const children = [];
    for (let i = 0; i < 7; i++) {
      children.push(
        <Descriptions.Item
          key={i}
          label={
            i === 6
              ? '营业执照'
              : shopOne.map((item) => {
                  if (item.key === i) {
                    return item.name;
                  } else {
                    return;
                  }
                })
          }
        >
          {i !== 6 ? (
            shopOne.map((item) => {
              if (item.key === i) {
                return <div key={item.key}> {item.value} </div>;
              } else {
                return;
              }
            })
          ) : (
            <Image
              height={200}
              src={`http://localhost:8090/dyh/upload_images/business/${business?.certificate}`}
            />
          )}
        </Descriptions.Item>,
      );
    }
    return children;
  };

  return (
    <div className={styles.container}>
      <TopBread lastRoute={'商品详情'} now={'店铺首页'} setColorParent={setColor} />
      <div className={styles.header}>
        <img
          src={`http://localhost:8090/dyh/upload_images/business/${business?.saleLogo}`}
          alt={'加载失败'}
          className={styles.logoImg}
        />

        <div className={styles.logoText}>
          <p className={styles.logoTop} style={{ color: colorStr(3) }}>
            {business?.saleName}
          </p>
          <p className={styles.logobottom} style={{ color: colorStr(3) }}>
            {/* {business?.salestate} */}
            保健品专卖
          </p>
        </div>
      </div>
      <div className={styles.content}>
        <Collapse
          accordion
          bordered={false}
          defaultActiveKey={'1'}
          style={{ backgroundColor: colorStr(1) }}
        >
          <Panel header="店铺简介" key="1" style={panelStyle}>
            <Descriptions title={''}>{getFields()}</Descriptions>
          </Panel>
          <Panel header="店铺内景" key="2" style={panelStyle}>
            <Image.PreviewGroup>
              {current.map((item) => (
                <Image
                  height={200}
                  src={`http://localhost:8090/dyh/upload_images/business/${item}`}
                  key={item}
                />
              ))}
            </Image.PreviewGroup>
          </Panel>
          <Panel header="店内热销" key="3" style={panelStyle}>
            {list.map((item) => {
              let curr = JSON.stringify(item.img)
                .replace('[', '')
                .replace(']', '')
                .replace(/"/g, '')
                .replace(/\\/g, '')
                .split(',');

              return (
                <img
                  src={`http://localhost:8090/dyh/upload_images/business/${curr[0]}`}
                  alt={'加载失败'}
                  onClick={() => {
                    history.push({
                      pathname: 'commodity',
                      query: {
                        lastRoute: '店铺首页',
                        id: item.id,
                      },
                    });
                  }}
                  className={styles.goodsImg}
                  key={item.id}
                />
              );
            })}
          </Panel>
        </Collapse>
        <div className={styles.goodsContent} style={{ backgroundColor: colorStr(1) }}>
          <div className={styles.tableTitle}>
            所有商品
            <span className={styles.triangleLittle}>ALL</span>
          </div>
          <div className={styles.goodsTable}>
            <GoodsDiv ifHomePage={'3'} goods={goodsList} />
            <div className={styles.tablePages}>
              <Pagination
                current={currentPage}
                hideOnSinglePage
                total={total}
                onChange={(e) => {
                  setCurrentPage(e);
                }}
              />
            </div>
          </div>
        </div>
      </div>

      {qs.role !== '3' && (
        <div className={styles.floatBtn}>
          <Popover content={content} title="">
            <img
              src={require('@/assets/images/菜单.svg')}
              className={styles.leftFloat}
              alt={'加载失败'}
            />
          </Popover>
          <img
            src={require('@/assets/images/向左指漂浮宇航员.svg')}
            className={styles.rightFloat}
            alt={'加载失败'}
          />
        </div>
      )}
      <Conversation
        receiveId={business?.userId ? business.userId : ''}
        color={color}
        business={business}
        visible={conversation}
        onCancel={() => {
          setConversation(false);
        }}
      />
      <RightFixed thisRoute={'店铺详情'} color={color} />
    </div>
  );
};

export default SaleOne;
